import { _decorator, Component, Vec3, Camera } from 'cc';
import { GameEventType } from '../Event/EnumDefine';
import { EventManager } from '../Event/EventManager';
import { DataConfig } from '../Config/DataConfig';

const { ccclass, property } = _decorator;
/** 屏幕抖动效果 */
@ccclass('CameraShakeEffect')
export class CameraShakeEffect extends Component {

    @property(Camera)
    camera: Camera = null;

    @property
    shakeIntensity: number = 10;

    @property
    shakeDuration: number = 0.5;

    @property
    shakeInterval: number = 0.05;

    private originalPos: Vec3 = new Vec3();
    private shakeTimer: number = 0;

    onLoad() {
        this.shakeDuration = 1;
        this.originalPos = this.camera.node.position.clone();
        EventManager.instance.registerEvent(GameEventType.Flash_Red_Effect, this.shake, this);
    }

    shake() {
        let dataCamera = DataConfig.camera;
        dataCamera.isShake = true;
        this.originalPos = new Vec3(dataCamera.posX, 0);

        this.shakeTimer = setInterval(() => {
            const offsetX = (Math.random() - 0.5) * this.shakeIntensity;
            const offsetY = (Math.random() - 0.5) * this.shakeIntensity;
            this.camera.node.setPosition(this.originalPos.x + offsetX, this.originalPos.y + offsetY, this.originalPos.z);
        }, this.shakeInterval * 1000);

        setTimeout(() => {
            clearInterval(this.shakeTimer);
            this.camera.node.setPosition(this.originalPos);
            dataCamera.isShake = false;
        }, this.shakeDuration * 1000);
    }
}
